package com.example.demo.controller;

import com.example.demo.entity.AjaxResult;
import com.example.demo.service.FirmwareUpgradeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class HelloController {

    @Autowired
    private FirmwareUpgradeService firmwareUpgradeService;

    @Value("${server.servlet.context-path}")
    private String ctxPath;

    @Value("${env.name}")
    private String envName;
    @GetMapping("/hello")
    @ResponseBody
    public String hello(){
        return "hello";
    }

    @GetMapping("/list")
    public String index(HttpServletRequest request, HttpServletResponse response, Model model){
        // 表格内容的遍历
        List<Map<String, Object>> flist = firmwareUpgradeService.findAll();
        model.addAttribute("flist", flist);
        model.addAttribute("ctxPath", ctxPath);
        model.addAttribute("envName", envName);
        return "page/list";
    }
    @GetMapping("/")
    public String gologin(Model model){
        model.addAttribute("_data", new HashMap<>());
        model.addAttribute("ctxPath", ctxPath);
        model.addAttribute("envName", envName);
        return "page/login";
    }
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(@RequestBody Map<String, Object> data, HttpSession session, HttpServletResponse response, Model model){
        if("admin".equals(data.get("usercode")) && "admin123".equals(data.get("password"))){
            session.setAttribute("usercode", data.get("usercode"));
            AjaxResult result = AjaxResult.success("登录成功");
            long token = System.currentTimeMillis();
            result.put("token", token);
            Cookie c = new Cookie("token", String.valueOf(token));
            response.addCookie(c);
            return result;
        }else{
            return AjaxResult.error("用户名或密码错误");
        }
    }
}
